package com.itljm.cxrMarket.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itljm.cxrMarket.common.PageResult;
import com.itljm.cxrMarket.common.Result;
import com.itljm.cxrMarket.entity.SysRole;
import com.itljm.cxrMarket.service.SysRoleService;
import com.itljm.cxrMarket.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @author ljm
 * @date 2024/11/27 16:44
 */
@RestController
@RequestMapping("/sysRole")
@CrossOrigin
public class SysRoleController {
    @Autowired
    private SysRoleService sysRoleService;

    // 分页查询
    @GetMapping("/info")
    public PageResult<SysRole> selectPageInfo(Integer pageNum, Integer pageSize,
                                              String roleName,String beginTime,String endTime) {
        if (pageNum == null) {
            pageNum = 0;
        }
        if (pageSize == null) {
            pageSize = 15;
        }
        Page<SysRole> rolePage = new Page<>(pageNum, pageSize);
        QueryWrapper<SysRole> wrapper = new QueryWrapper<>();
        wrapper.eq("1",1);
        if (StringUtils.isNotEmpty(roleName)) {
            wrapper.like("description", roleName);
        }
        if (StringUtils.isNotEmpty(beginTime)) {
            wrapper.ge("update_time", beginTime);
        }
        if (StringUtils.isNotEmpty(endTime)) {
            wrapper.le("update_time", endTime);
        }

        List<SysRole> roleList = sysRoleService.selectRolePage(rolePage, wrapper);
        return new PageResult<>(roleList,rolePage.getTotal());
    }

    // 获取所有角色
    @GetMapping("/all")
    public Result selectAllRole() {
        List<SysRole> roles = sysRoleService.selectAllRole();
        return Result.ok(roles);
    }

    @PostMapping("/insert")
    public Result insert(@RequestBody SysRole sysRole) {
        sysRole.setCreateTime(new Date());
        boolean b = sysRoleService.insertRole(sysRole);
        if (!b) {
            return Result.fail("添加失败");
        }
        return Result.ok("添加成功");
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        boolean b = sysRoleService.deleteRole(id);
        if (!b) {
            return Result.fail("删除失败");
        }
        return Result.ok("删除成功");
    }

    @PutMapping("/update")
    public Result update(@RequestBody SysRole sysRole) {
        sysRole.setUpdateTime(new Date());
        boolean b = sysRoleService.updateRole(sysRole);
        if (!b) {
            return Result.fail("修改失败");
        }
        return Result.ok("修改成功");
    }
}
